package com.zysc.processflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zysc.processflow.common.util.SendSMSUtils;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.*;
import com.zysc.processflow.mapper.OrganizationMapper;
import com.zysc.processflow.mapper.PersonMapper;
import com.zysc.processflow.service.IPersonService;
import com.zysc.processflow.common.base.BaseService;
import com.zysc.processflow.service.IPersonorgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员表 服务实现类
 * </p>
 *
 * @author 正元智慧城市_
 * @since 2022-11-23
 */
@Service
public class PersonServiceImpl extends BaseService<PersonMapper, Person> implements IPersonService {
    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    IPersonorgService personorgService;
    @Autowired
    SendSMSUtils smsUtils;

    @Override
    public List<Person> GetPersonList(IPage<Person> page, String username, String orgid, String currentorgid, String currentorgtype, String orgname) {
        List<Person> personList = new ArrayList<>();
        //如果是政府,那么直接查就行
        if (!StringUtils.isNull(currentorgtype) && currentorgtype.equals("3")){
            return this.baseMapper.GetPersonList(page,username,orgid,null,orgname);
        }
        //添加权限逻辑，筛选出只符合当前组织机构id的人员
        List<String> orgids = this.getAllOrgFlowedByorgId(currentorgid,currentorgtype).stream().map(item->item.getId()).collect(Collectors.toList());
        if(orgids.size()>0){
            personList = this.baseMapper.GetPersonList(page,username,orgid,orgids,orgname);
        }
        return personList;
    }

    @Override
    public Boolean saveOrUpdatePersonInfo(Person entity) {
        boolean b1 = true;//保存person表信息成功标志
        boolean b2 = true;//删除原来personorg表信息成功标志
        boolean b3 = true;//新增personorg表信息成功标志
        //1.首先保存人员信息
        b1 = this.saveOrUpdate(entity);

        if(!StringUtils.isNull(entity.getOrgid())){
            //2.生成一条personorg对象
            Personorg personorg = new Personorg();
            personorg.setPersonid(entity.getId());
            personorg.setPersonname(entity.getName());
            personorg.setOrgid(entity.getOrgid());
            Organization organization = organizationMapper.selectById(entity.getOrgid());
//        if(organization==null){
//            throw new RuntimeException("未找到组织机构信息");
//        }
//        personorg.setOrgname(organization.getName());
            if(organization!=null){
                personorg.setOrgname(organization.getName());
            }

            //3.删除personorg表中，该单位，该人员的信息（防止产生重复数据）
            LambdaQueryWrapper<Personorg> perorgqw = new LambdaQueryWrapper<>();
            perorgqw.eq(Personorg::getPersonid, entity.getId())
                    .eq(Personorg::getOrgid,entity.getOrgid());
            List<Personorg> perorgList = personorgService.list(perorgqw);
            if(perorgList.size()>0){
                b2 = personorgService.remove(perorgqw);
            }

            //4.判断是新增还是修改
            String personorgid = entity.getPersonorgid();
            if(StringUtils.isNull(personorgid)){
                b3 = personorgService.save(personorg);
            }else{
                personorg.setId(personorgid);//如果是修改，那么将以前的覆盖掉
                b3 = personorgService.saveOrUpdate(personorg);
            }
        }
        //5.返回结果
        return b1&&b2&&b3;
    }

    @Override
    public Boolean deletePersonInfo(Person entity) {
        boolean b1 = true;//删除原来personorg表信息成功标志
        boolean b2 = true;//新增personorg表信息成功标志
        //1.删除personorg里的该人员id和单位id对应的数据
        LambdaQueryWrapper<Personorg> perorgqw = new LambdaQueryWrapper<>();
        perorgqw.eq(Personorg::getPersonid, entity.getId())
                .eq(Personorg::getOrgid,entity.getOrgid());
        List<Personorg> perorgList = personorgService.list(perorgqw);
        if(perorgList.size()>0){
            b1 = personorgService.remove(perorgqw);
        }
        //2.判断personorg表里还有没有该人员在其他单位的信息，如果没了，那么把person表的这个人删除
        perorgqw.clear();
        perorgqw.eq(Personorg::getPersonid, entity.getId());
        List<Personorg> otherPerorgList = personorgService.list(perorgqw);
        if(otherPerorgList.size()==0){
            b2 = this.removeById(entity.getId());
        }
        return b1&&b2;
    }

    @Override
    public List<Person> getPersonListByOrgId(String orgid) {
        if(StringUtils.isNull(orgid)){
            return new ArrayList<>();
        }
        List<Organization> organizationList = new ArrayList<>();
        Organization currentOrg = organizationMapper.selectById(orgid);
        if(currentOrg==null){
            currentOrg = organizationMapper.getOrgByTyshxydm(orgid);
            if(currentOrg==null){
                return new ArrayList<>();
            }
        }
        if(!StringUtils.isNull(currentOrg.getType())&&(currentOrg.getType().equals("3")||currentOrg.getType().equals("1")||currentOrg.getType().equals("4"))){
            if(currentOrg!=null){
//                List<String> pathList = this.getOwnerArray(orgid,null);
//                String path = String.join("#",pathList);
//                //String path = currentOrg.getPath();
//                if(!StringUtils.isNull(path)){
//                    LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
//                    queryWrapper.likeRight(Organization::getPath,path);
//                    List<Organization> list = organizationMapper.selectList(queryWrapper);
//                    organizationList = list;
//                }
                if(currentOrg.getType().equals("1") && !StringUtils.isNull(currentOrg.getCode())){
                    LambdaQueryWrapper<Organization> qw = new LambdaQueryWrapper<>();
                    qw.eq(Organization::getCode,currentOrg.getCode());
                    organizationList = organizationMapper.selectList(qw);
                }else{
                    LambdaQueryWrapper<Organization> qw = new LambdaQueryWrapper<>();
                    qw.eq(Organization::getFatherid,currentOrg.getId());
                    organizationList = organizationMapper.selectList(qw);
                    organizationList.add(currentOrg);
                }
            }
            if(organizationList.size()>0){
                List<String> orgids = organizationList.stream().map(item->item.getId()).collect(Collectors.toList());
                List<Person> list = this.baseMapper.getPersonListByOrgIds(orgids);
                return list;
            }else{
                return new ArrayList<>();
            }
        }else{
            return this.baseMapper.getPersonListByOrgId(orgid);
        }
    }

    public List<String> getOwnerArray(String orgid,String currentorgid) {
        List<String> result =new ArrayList<>();
        String temp = orgid;
        while(true){
            Organization organization = organizationMapper.selectById(temp);
            if(organization==null){
                break;
            }else{
                result.add(temp);
                temp = organization.getFatherid();
                if((!StringUtils.isNull(currentorgid) && organization.getId().equals(currentorgid) )){
                    break;
                }
            }
        }
        Collections.reverse(result);
        return result;
    }

    @Override
    public List<Person> getPersonListByOrgIdAndRoleId(String orgid, String roleid) {
        if(StringUtils.isNull(orgid) || StringUtils.isNull(roleid)){
            return new ArrayList<>();
        }
        List<Organization> organizationList = new ArrayList<>();
        Organization currentOrg = organizationMapper.selectById(orgid);
        if(currentOrg==null){
            currentOrg = organizationMapper.getOrgByTyshxydm(orgid);
            if(currentOrg==null){
                return new ArrayList<>();
            }
        }
        //如果组织机构是政府，企业，园区，那么查询时，查询其和其子组织机构的所有数据
        if(!StringUtils.isNull(currentOrg.getType())&&(currentOrg.getType().equals("3")||currentOrg.getType().equals("1")||currentOrg.getType().equals("4"))){
            if(currentOrg!=null){
                //如果是企业,那么可能部门套部门,需要拿到所有的组织机构
                if(currentOrg.getType().equals("1") && !StringUtils.isNull(currentOrg.getCode())){
                    LambdaQueryWrapper<Organization> qw = new LambdaQueryWrapper<>();
                    qw.eq(Organization::getCode,currentOrg.getCode());
                    organizationList = organizationMapper.selectList(qw);
                }else{
                    //如果是政府,那么拿到所有其后代部门,优先根据path查询
                    if(!StringUtils.isNull(currentOrg.getPath()) && currentOrg.getPath().startsWith("sys_330801#") && currentOrg.getPath().endsWith("#"+currentOrg.getId())){
                        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.likeRight(Organization::getPath,currentOrg.getPath());
                        List<Organization> list = organizationMapper.selectList(queryWrapper);
                        organizationList = list;
                    }else{
                        //如果走这个else,现在只有一层,注意
                        LambdaQueryWrapper<Organization> qw = new LambdaQueryWrapper<>();
                        qw.eq(Organization::getFatherid,currentOrg.getId());
                        organizationList = organizationMapper.selectList(qw);
                        organizationList.add(currentOrg);
                    }
                }
            }
            if(organizationList.size()>0){
                List<String> orgids = organizationList.stream().map(item->item.getId()).collect(Collectors.toList());
                List<Person> list =  this.baseMapper.getPersonListByOrgIdsAndRoleId(orgids,roleid);
                if(list.size()>50){//一个企业，一个重要角色没有这么多人的，如果有，那么报错。。。为了防止程序异常，短信发错,等程序稳定了再删除这个逻辑
                    smsUtils.sendMsg("18854805007","一个组织机构，一个重要角色没有这么多人的，如果有，那么报错。。。为了防止程序异常，短信发错,等程序稳定了再删除这个逻辑");
                    throw new RuntimeException("系统出现错误，请联系管理员");
                }
                for (Person per : list) {
                    per.setOrgname(currentOrg.getName());
                }
                return list;
            }else{
                return new ArrayList<>();
            }
        }else{//如果是小部门，区县，等等
            List<Person> tmp =  this.baseMapper.getPersonListByOrgIdAndRoleId(orgid,roleid);
            for (Person per : tmp) {
                per.setOrgname(currentOrg.getName());
            }
            return tmp;
        }
    }

    @Override
    //数据权限：根据一个orgid获取该显示的数据,与权限有关的都走这个方法，拦截这个方法即可
    public List<Organization> getAllOrgFlowedByorgId(String currentorgid,String currentorgtype) {
        //这里默认currentorgid是政府或者企业id，而不是小部门的id,如果不是，需要再增加逻辑
        if(StringUtils.isNull(currentorgid)){
            return new ArrayList<Organization>();
        }
        String orgid = "";
        if(currentorgtype.equals("1")||currentorgtype.equals("2")){//企业，承包商侧可能传的是企业社会信用代码
            //1.根据单位id查
            LambdaQueryWrapper<Organization> orgqw = new LambdaQueryWrapper<>();
            orgqw.eq(Organization::getCode, currentorgid);
            List<Organization> orgList = organizationMapper.selectList(orgqw);
            if(orgList.size()>0){
                orgid = orgList.get(0).getId();
            }else{
                orgid = currentorgid;
            }
        }else{//政府测的，先给全部权限
            orgid = "sys_330801";
        }
        if(StringUtils.isNull(orgid)){
            return new ArrayList<Organization>();
        }
        /*当前组织机构数据结构图：
         * 衢州（市区）
         *   |-江山县（区县）
         *           |-江山市园区（园区）
         *                 |-江山市园区政府（政府4）（只是目前还没有这种园区下的政府，以后可能会有）
         *                       |-组织人事处(园区政府小部门41)
         *                 |-江山A企业(企业1)
         *                       |-消防部（企业小部门11）
         *           |-江山市应急管理局(政府3)
         *                 |-安全管理部（政府小部门31）
         * */
        List<Organization> organizationList = new ArrayList<>();
        Organization currentOrg = organizationMapper.selectById(orgid);
        if(currentOrg!=null){
            //查询所有子组织机构，包括自己
            String path = currentOrg.getPath();
            if(!StringUtils.isNull(path)){
                LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.likeRight(Organization::getPath,path);
                List<Organization> list = organizationMapper.selectList(queryWrapper);
                organizationList = list;
            }
//            List<Organization> allOrgList = organizationMapper.selectList(null);
//            organizationList.add(currentOrg);
//            organizationList = getChildrenByOrg(currentOrg.getId(), organizationList,allOrgList);
        }
        return organizationList;
    }

    @Override
    public List<Person> getPersonListByOrgIdsAndRoleId(List<String> orgids, String roleid) {
        return this.baseMapper.getPersonListByOrgIdsAndRoleId(orgids,roleid);
    }

    public List<Organization> getChildrenByOrg(String orgid,List<Organization> result,List<Organization> allOrgList){

//        LambdaQueryWrapper<Organization> qw = new LambdaQueryWrapper<>();
//        qw.eq(Organization::getFatherid,orgid);
//        List<Organization> children = organizationMapper.selectList(qw);

        List<Organization> children = allOrgList.stream().filter(item->!StringUtils.isNull(item.getFatherid()) && item.getFatherid().equals(orgid)).collect(Collectors.toList());

        children.stream().forEach(child->{
            result.add(child);
            List<Organization> temp =getChildrenByOrg(child.getId(),result,allOrgList);
        });
        return result;
    }

}
